#!/bin/bash
# Test hierarchies mounted multiple times (one hierarchy mounted 99 times)
# - cgsnapshot
# - cgconfigparser
# - lssubsys

. `dirname $0`/../testenv.sh

# cgconfigparser cannot handle more than 100 mount points :-(
COUNT=99

function check_config()
{
	CONFIG=$1
	# check basic sanity of generatet cgconfig.conf file
	#  - it has expected number of mount points
	if [ `grep '=' < $CONFIG | wc -l` -ne $(($COUNT*4)) ]; then
		die "wrong number of mount points in $CONFIG"
	fi

	#  - it has mount section
	grep "mount" >/dev/null <$CONFIG \
		|| die "cgsnapshot failed, no mount section found in $CONFIG"

	#  - it has 99 different mount points
	for i in `seq $COUNT`; do
		grep "cpuacct$i" >/dev/null <$CONFIG \
			|| die "cgsnapshot failed, no cpuacct$i found in $CONFIG"
	done
}

for i in `seq $COUNT`; do
	mkdir -p $TMP/cgroups/cpuacct$i 2>/dev/null
	mount -t cgroup -o cpuacct,cpuset,memory,freezer cpuacct$i \
			$TMP/cgroups/cpuacct$i \
		|| die "Mount $i failed"
done

# check lssubsys
# plain lssubsys - only one line with 4 controllers is expected
$TOOLSDIR/lssubsys >$TMP/subsys1.out \
	|| die "plain lssubsys failed"
[ `wc -l <$TMP/subsys1.out` -eq 1 ] \
	|| die "unexpected output of plan lssubsys"

# lssubsys -m - first mount point is returned
$TOOLSDIR/lssubsys -m >$TMP/subsys2.out \
	|| die "lssubsys -m failed"
[ `wc -l <$TMP/subsys2.out` -eq 1 ] \
	|| die "unexpected output of lssubsys -m"
grep <$TMP/subsys2.out cpuacct1 >/dev/null \
	|| die "lssubsys -m does not show the first mount point"

# lssubsys -M - all mount points are returned
$TOOLSDIR/lssubsys -M >$TMP/subsys3.out \
	|| die "lssubsys -M failed"
[ `wc -l <$TMP/subsys3.out` -eq $COUNT ] \
	|| die "unexpected output of lssubsys -M"
for i in `seq $COUNT`; do
	grep <$TMP/subsys3.out cpuacct$i >/dev/null \
		|| die "lssubsys -m does not show cpuacct$i"
done

# check cgsnapshot
$TOOLSDIR/cgsnapshot -b $CONFIGDIR/cgsnapshot_blacklist.conf >$TMP/snapshot.conf \
	|| die "cgsnapshot failed"

check_config $TMP/snapshot.conf

$TOOLSDIR/cgclear || die "cgclear 1 failed"

# check cgconfigparser - try to parse the generated config
$TOOLSDIR/cgconfigparser -l $TMP/snapshot.conf \
	|| die "cgconfigparser failed to parse the snapshot"

# and make its snapshot again
$TOOLSDIR/cgsnapshot -b $CONFIGDIR/cgsnapshot_blacklist.conf >$TMP/snapshot2.conf \
	|| die "cgsnapshot2 failed"

check_config $TMP/snapshot2.conf

$TOOLSDIR/cgclear

cleanup
exit 0
